package org.orarriinae.common.utils.dto;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.collections4.CollectionUtils;
import org.orarriinae.common.base.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * DTO 工具类，提供DTO到Bean的转换，和Bean到DTO的转换
 *
 * @author Wang Chengwei
 * @since 1.0
 */
public class DtoUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(DtoUtils.class);

    private DtoUtils() {
    }

    public static <T, R> T transform(Class<T> clazz, R bean) {
        T entity = create(clazz);
        BeanUtils.copyProperties(bean, entity);
        return entity;
    }

    public static <T, R> List<T> transformList(Class<T> clazz, List<R> beans) {
        if (CollectionUtils.isEmpty(beans)) {
            return Collections.emptyList();
        }
        List<T> list = new ArrayList<>();
        for (Object bean : beans) {
            T entity = transform(clazz, bean);
            list.add(entity);
        }

        return list;
    }

    public static <T, R> IPage<T> transformPageList(Class<T> clazz, IPage<R> beanPage) {
        List<T> records = transformList(clazz, beanPage.getRecords());
        IPage<T> page = new Page<>(beanPage.getCurrent(), beanPage.getSize(), beanPage.getTotal());
        page.setRecords(records);
        return page;
    }

    public static <T> T create(Class<T> clazz){
        try {
            return clazz.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            LOGGER.warn(e.getMessage(), e);
            throw new ServiceException("无法实例化类");
        }
    }

}
